/**
 * Created by KaiBo on 2016/7/19.
 */

var workpath = '/./';  //项目ROOT
//添加规格项目
var selectArr = new Array("颜色", "尺寸", "尺码", "规格", "款式", "净含量", "种类", "内存", "版本", "容量");
var specArray0 = new Array();//规格1的数组
var specArray1 = new Array();//规格2的数组
var specArray2 = new Array();//规格3的数组
var specImgArray = new Array();//规格图片的数组
var specImgUnidArray = new Array();//规格图片ID的数组
var checkbox = false;  //判断checkbox是否选中

/**
 * 构建表格
 * @param $form 表单
 * @param first 规格的位置
 * @param $table 表格
 */
function showTable($form, first, $table,infoArray) {
    var spec1len = specArray0.length > 0 ? specArray0.length : 1;//数组1长度
    var spec2len = specArray1.length > 0 ? specArray1.length : 1;//数组2长度
    var spec3len = specArray2.length > 0 ? specArray2.length : 1;//数组3长度
    var sum = spec1len * spec2len * spec3len;

    var second = first + 1;
    var third = first + 2;
    var spec1 = '<td>' + $form.children(".spec:nth-child(" + first + ")").find("select").val() + '</td>';
    var spec2 = '<td>' + $form.children(".spec:nth-child(" + second + ")").find("select").val() + '</td>';
    var spec3 = '<td>' + $form.children(".spec:nth-child(" + third + ")").find("select").val() + '</td>';


    spec1 = specArray0.length > 0 ? spec1 : " ";
    spec2 = specArray1.length > 0 ? spec2 : " ";
    spec3 = specArray2.length > 0 ? spec3 : " ";


    var html = '<tr>' + spec1 + spec2 + spec3 + '<td >价格（元）</td><td>库存</td><td>商家编码</td></tr>';

    $table.html(html);
    var l = 0;
    for (var i = 0; i < spec1len; i++) {
        var name = "";
        var spec1Name = "";
        if (specArray0.length > 0) {
            spec1 = specArray0[i][1];
            name += specArray0[i][0] + i + "-";
            spec1Name = name;
        }
        for (var j = 0; j < spec2len; j++) {
            var spec2Name = "";
            name = spec1Name;
            if (specArray1.length > 0) {
                spec2 = specArray1[j][1];
                name += specArray1[j][0] + j + "-";
            }
            spec2Name = name;
            for (var k = 0; k < spec3len; k++) {
                name = spec2Name;
                html = '<tr>';
                if (specArray0.length > 0) {
                    html += '<td >' + spec1 + '</td>';
                }
                if (specArray1.length > 0) {
//                            if (j % (sum / specArray1.length) == 0) {
                    html += '<td >' + spec2 + '</td>';
//                            }
                }
                if (specArray2.length > 0) {
                    html += '<td >' + specArray2[k][1] + '</td>';
                    name += specArray2[k][0] + k + "-";
                }

                name = name.replace(/\[/g, "");
                name = name.replace(/\]/g, "");
                name = name.substr(0, name.length - 1);
                name = name.trim();

                var goodsprice = "";
                var stock = "";
                var mallid = "";
                if(infoArray!=null && infoArray.length > 0){
                    goodsprice = infoArray[l].goodsprice;
                    stock = infoArray[l].stock;
                    mallid = infoArray[l].mallid;
                }

                if (name != "") {
                    html += '<td width="100px"><input type="text" name=' + name + ' value="'+goodsprice+'" class="form-control" placeholder=""></td>';
                    html += '<td width="80px"><input type="text" name=' + name + ' value="'+stock+'" class="goods-stock form-control" placeholder=""></td>';
                    html += '<td width="80px"><input type="text" name=' + name + ' value="'+mallid+'" class="form-control" placeholder=""></td>';
                    l++;
                }

                html += '</tr>';
                $table.append(html);
            }
        }
    }
}
//库存取消焦点事件计算库存
    $(document).on("blur",".goods-stock",function(){
        var stockSum = 0;
        $(".table tr").each(function(){
            var $elem = $(this);
            var stock = $elem.find(".goods-stock").val();
            if(stock == null || stock == "" ||stock == undefined){
                stock = 0;
            }
            stockSum += parseInt(stock);
        });
        $("#stocksum").val(stockSum);
    });

//添加规格项
$(".add-group").click(function () {
    var index = $(this).parents("form").children(".spec").length;//获取规格数
    index++;
    $("#normsnum").val(index);

    var myDate = new Date();
    var s = myDate.getTime().toString();
    s = "S" + index;

    var html = '<div class="form-group spec">';
    html += '   <div class="col-sm-4">';
    html += '       <select name=' + s + ' class="form-control">';
    for (var i = 0; i < selectArr.length; i++) {
        html += '<option value=' + selectArr[i] + '>' + selectArr[i] + '</option>';
    }
    html += '       </select>';
    html += '   </div>';
    html += '   <div class="col-sm-2  text-left">';
    html += '       <div class="checkbox">';
    html += '           <label>';
    html += '               <input class="checkbox-item" type="checkbox"> 添加规格图片';
    html += '           </label>';
    html += '       </div>';
    html += '   </div>';
    html += '   <div class="col-sm-4  text-left">';
    html += '       <div class="input-group">';
    html += '           <input type="text" class="form-control" placeholder="添加规格项">';
    html += '           <span class="input-group-btn">';
    html += '               <button class="btn add-spec-option btn-default" type="button">添加</button>';
    html += '           </span>';
    html += '       </div>';
    html += '   </div>';
    html += '   <div class="col-sm-2 text-right">';
    html += '      <h5><span class="glyphicon close-spec glyphicon-remove-circle"></span></h5>';
    html += '   </div>';
    html += '   <div class="col-sm-12 text-left spec-list">';
    html += '        <div><button type="button" class="btn add-spec-item btn-default" >+添加</button></div>';
    html += '   </div>';
    html += '</div>';


    $(this).parents(".form-group").before(html);
    if (index >= 3) {
        $("#add-group").slideUp("slow");
        index = 3;
    }
});

//添加下拉菜单选项
$(document).on("click", ".add-spec-option", function () {
    var $elem = $(this);
    var val = $elem.parent().prev("input").val();
    var $select = $elem.parents(".spec").find("select");

    $elem.parent().prev("input").val("");
    if (selectArr.indexOf(val) < 0) {
        selectArr.push(val);
        alert("添加成功");
    } else {
        alert("已存在此规格项");
        return;
    }
    $select.html("");
    for (var i = 0; i < selectArr.length; i++) {
        var html = '<option value=' + selectArr[i] + '>' + selectArr[i] + '</option>';
        $select.append(html);
    }
    //$select.val(val);
});


//弹出提示框
var content = '<div class="row">';
content += '  <div class="col-xs-8"><input type="text"  class="form-control" placeholder="添加规格值"></div>';
content += '<div class="col-xs-4"><button type="button" class="btn btn-ok btn-primary">确定</button></div>';
content += '</div>';

//动态添加弹窗插件
$(document).on("mouseover", ".add-spec-item", function () {
    var $elem = $(this);
    $elem.popover({
        html: true,
        content: content
    });
});

//判断元素是否在数组中
function contains(arry, elem) {
    var i = arry.length;
    while (i--) {
        if (arry[i][1] == elem) {
            return true;
        }
    }
    return false;
}


//添加规格值
//规格确认点击事件
$(document).on("click", ".btn-ok", function () {
    var $elem = $(this);
    var $add = $elem.parents(".popover").prev(".add-spec-item");//添加按钮
    var index = $elem.parents("form").children(".spec").index($add.parents(".spec"));//获取触发事件的位置
    var specVal = $elem.parent("div").prev().children("input").val();//获取值

    specVal = specVal.trim();//去除空格
    if (specVal == "") {
        return;
    }
    //判断是否存在相同规格值
    switch (index) {
        case 0:
            if (contains(specArray0, specVal)) {
                alert("已存在此规格值");
                return;
            }
            break;
        case 1:
            if (contains(specArray1, specVal)) {
                alert("已存在此规格值");
                return;
            }
            break;
        case 2:
            if (contains(specArray2, specVal)) {
                alert("已存在此规格值");
                return;
            }
            break;
        default:
            alert("未知错误！");
    }

    var Dindex = 0; //计算规格值数量
    Dindex = $add.parent("div").siblings(".spec-item").length;

    var detail = $(this).parents(".spec").find("select").attr("name");
    detail = detail.substr(1, detail.length - 1);
    var Idetail = "I" + detail; //图片路径
    detail = "D" + detail;

    var html = "";
    if (checkbox) {
        html = '<div class="spec-item active">';
        html += '    <div class="spec-img">';
        html += '        <div class="add-img">';
        html += '            <img title="点击更换" class="img-responsive" src="" alt="">';
        html += '        </div>';
        html += '    </div>';
    } else {
        html = '<div class="spec-item">';
    }
    html += '       <input type="text" id=' + Idetail + Dindex + ' hidden name=' + Idetail + ' >';
    html += '       <input type="text" hidden name=' + detail + ' value=' + specVal + '>';
    html += '       <input type="button" data-img=' + Idetail + Dindex + ' name=' + detail + ' class="btn btn-block btn-default" value=' + specVal + '>';
    html += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
    html += '</div>';


    var html2 = '<div class="spec-item">';
    html2 += '       <input type="text" hidden name=' + detail + ' value=' + specVal + '>';
    html2 += '       <input type="button" name=' + detail + ' class="btn btn-block btn-default" value=' + specVal + '>';
    html2 += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
    html2 += '  </div>';

    $add.popover('destroy');//隐藏并销毁元素的弹出框

    var temp = new Array();
    temp.push(detail);
    temp.push(specVal);
    switch (index) {
        case 0:
            $add.parent("div").before(html);//显示规格值
            specArray0.push(temp);
            break;
        case 1:
            $add.parent("div").before(html2);//显示规格值
            specArray1.push(temp);
            break;
        case 2:
            $add.parent("div").before(html2);//显示规格值
            specArray2.push(temp);
            break;
        default:
            alert("未知错误！");
    }

    showTable($("form"), 8, $(".table"));
});

//重构规格项
function InitSpecItem() {
    $(".spec").each(function () {
        var Sindex = $(this).parents("form").children(".spec").index($(this));//获取规格位置
        var $add = $(this).find(".add-spec-item");//添加按钮
        var $specList = $(this).find(".spec-list");//规格项列表
        $specList.children(".spec-item").remove();
        Sindex += 1;
        var Idetail = "I" + Sindex;
        var Ddetail = "D" + Sindex;

        var html = " ";
        switch (Sindex) {
            case 1:
                for (var i in specArray0) {
                    html = " ";
                    var Dindex = $specList.children(".spec-item").length;//计算规格值数量
                    var src = "";
                    var imgUnid = "";
                    if(specImgArray != null && specImgArray.length > 0){
                        src = specImgArray[i];
                    }
                    if(specImgUnidArray !=null && specImgUnidArray.length > 0){
                        imgUnid = specImgUnidArray[i];
                    }
                    if (checkbox) {
                        html = '<div class="spec-item active">';
                        html += '    <div class="spec-img">';
                        html += '        <div class="add-img">';
                        html += '            <img title="点击更换" class="img-responsive" src="' + src + '" alt="">';
                        html += '        </div>';
                        html += '    </div>';
                    } else {
                        html = '<div class="spec-item">';
                    }
                    html += '       <input type="text" id=' + Idetail + Dindex + ' hidden name="' + Idetail + '" value="' + imgUnid + '" >';
                    html += '       <input type="text" hidden name=' + Ddetail + ' value=' + specArray0[i][1] + '>';
                    html += '       <input type="button" data-img=' + Idetail + Dindex + ' name=' + Ddetail + ' class="btn btn-block btn-default" value=' + specArray0[i][1] + '>';
                    html += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
                    html += '</div>';
                    $add.parent("div").before(html)
                }
                break;
            case 2:
                for (var i in specArray1) {
                    html = '<div class="spec-item">';
                    html += '       <input type="text" hidden name=' + Ddetail + ' value=' + specArray1[i][1] + '>';
                    html += '       <input type="button" name=' + Ddetail + ' class="btn btn-block btn-default" value=' + specArray1[i][1] + '>';
                    html += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
                    html += '  </div>';
                    $add.parent("div").before(html)
                }
                break;
            case 3:
                for (var i in specArray2) {
                    html = '<div class="spec-item">';
                    html += '       <input type="text" hidden name=' + Ddetail + ' value=' + specArray2[i][1] + '>';
                    html += '       <input type="button" name=' + Ddetail + ' class="btn btn-block btn-default" value=' + specArray2[i][1] + '>';
                    html += '       <span class="glyphicon close-spec-item glyphicon-remove-circle"></span>';
                    html += '  </div>';
                    $add.parent("div").before(html)
                }
                break;
            default:
                break;
        }
        //Sindex  = Sindex+1;
        //var Sname = "S"+Sindex;
        //var Dname = "D"+Sindex;
        //var Iname = "I"+Sindex;
        //$(this).find("select").attr("name",Sname);
        //$(this).find("input[name*='D']").attr("name",Dname);
        //$(this).find("input[name*='I']").attr("name",Iname);
    });
}

//删除规格值
$(document).on("click", ".close-spec-item", function () {
    var $elem = $(this);
    var index = $elem.parents("form").children(".spec").index($elem.parents(".spec"));//获取触发事件的位置
    var specVal = $elem.parents("div").children("input").val();//获取值

    var Dindex = $elem.parents(".spec-list").children(".spec-item").index($elem.parents(".spec-item"));

    switch (index) {
        case 0:
            //$add.parent("div").before(html);//显示规格值

            specArray0.splice(Dindex, 1);

            specImgArray.splice(Dindex, 1);//移除规格图片数组
            specImgUnidArray.splice(Dindex, 1);//移除规格图片id数组
            break;
        case 1:
            //$add.parent("div").before(html2);//显示规格值
            specArray1.splice(Dindex, 1);
            break;

        case 2:
            //$add.parent("div").before(html2);//显示规格值
            specArray2.splice(Dindex, 1);
            break;
        default:
            alert("未知错误！");
    }

    $elem.parents(".spec-item").remove();
    InitSpecItem();
    showTable($("form"), 8, $(".table"));
});


//减少规格项目
$(document).on("click", ".close-spec", function () {
    var $elem = $(this);
    var index = $elem.parents("form").children(".spec").length;//获取规格数

    var $spec = $elem.parents(".spec");
    var Sindex = $elem.parents("form").children(".spec").index($spec);//获取规格位置
    var $add = $(this).parents(".spec").find(".add-spec-item");
    $add.popover('destroy');//隐藏并销毁元素的弹出框

    switch (Sindex) {
        case 0:
            specArray0 = specArray1;
            specArray1 = specArray2;
            specArray2 = [];

            specImgArray = [];//清空规格图片数组
            specImgUnidArray = [];//清空规格图片id数组
            break;
        case 1:
            specArray1 = specArray2;
            specArray2 = [];
            break;
        case 2:
            specArray2 = [];
            break;
        default:
            alert("未知错误！");
    }

    $("#add-group").slideDown("slow");
    $(this).parents(".form-group").remove();
    index = $(this).parents("form").children(".spec").length;//获取规格数
    $("#normsnum").val(index);

    //更新下拉菜单name和图片等name
    $(".spec").each(function () {
        Sindex = $(this).parents("form").children(".spec").index($(this));//获取规格位置
        Sindex = Sindex + 1;
        var Sname = "S" + Sindex;
        var Dname = "D" + Sindex;
        var Iname = "I" + Sindex;
        $(this).find("select").attr("name", Sname);
        $(this).find("input[name*='D']").attr("name", Dname);
        $(this).find("input[name*='I']").attr("name", Iname);
    });
    checkbox = false;  //判断checkbox是否选中
    InitSpecItem();
    showTable($("form"), 8, $(".table"));
});

//重新选择下拉菜单
$(document).on("change", " .spec select", function () {
    var $elem = $(this);
    var $spec = $elem.parents(".spec");
    var Sindex = $elem.parents("form").children(".spec").index($spec);//获取规格位置

    switch (Sindex) {
        case 0:
            specArray0 = [];
            break;
        case 1:
            specArray1 = [];
            break;
        case 2:
            specArray2 = [];
            break;
        default:
            alert("未知错误！");
    }

    var $speclist = $spec.find(".spec-list");
    $speclist.children(".spec-item").remove();

    showTable($("form"), 8, $(".table"));
});

//复选框显示规格图片
$(document).on("change", ".spec .checkbox-item", function () {
    var $specItem = $(this).parents(".spec").children(".spec-list").find(".spec-item");
    var $add = $(this).parents(".spec").find(".add-spec-item");
    $add.popover('destroy');//隐藏并销毁元素的弹出框

    var html = '<div class="spec-img">';
    html += '   <div class="add-img">';
    html += '        <img title="点击更换" class="img-responsive" src="" alt="">';
    html += '    </div>';
    html += '   </div>';
    if ($(this).attr("checked")) {
        //$specItem.removeClass("active");
        //$specItem.each(function () {
        //    $(this).children(".spec-img").remove();
        //});

        $(this).attr("checked", false);
        checkbox = false;
    } else {
        //$specItem.addClass("active");
        //$specItem.each(function () {
        //    $(this).prepend(html);
        //});
        $(this).attr("checked", true);
        checkbox = true;
    }
    InitSpecItem();
});

//删除商品图片
$(document).on("click", ".close-goods-img", function () {
    var $elem = $(this);
    var $imgList = $elem.parents(".goods-img-list");
    var index = $imgList.children(".goods-img-item").index($elem.parent(".goods-img-item"));
    var sum = $imgList.children(".goods-img-item").length;
    index = index + sum + 2;
    if (confirm("确认移除？")) {
        var $goodsid = $("#goodsid").val();
        var $goodspicid = $imgList.children("input:nth-child(" + index + ")").val();

        $.ajax({
            type: "POST",
            url: workpath+"Admin/Goods/UpdateCommodityPicDEL",
            data: {
                goodsid: $goodsid,
                goodspicid: $goodspicid,
            },
            dataType: "json",
            success: function (result) {
                $imgList.children("input:nth-child(" + index + ")").remove();
                $elem.parent(".goods-img-item").remove();
            },
            error: function () {
                alert('删除失败');
            }
        });
    }
});

//修改商品
$(".btn-update").click(function () {
    var json = $('#Frm').FrmJSON();
    $.ajax({
        type: "POST",
        url: workpath+"Admin/Goods/editGoods",
        data: {
            dataform: json,
        },
        dataType: "json",
        success: function (result) {
            alert(result.info);
            window.location.href = workpath+"Admin/Goods/index";
        },
        error: function () {
            alert('修改失败');
        }
    });
});


function UpdateFolders() {
    /*获取文件夹列*/
    $.post(workpath+"Admin/Picasa/Folders", {}, function (data) {
        var folder = eval(data);
        var html = '';
        for (var i = 0; i < folder.length; i++) {
            html += '<a href="#" data-id="';
            if (folder[i]['unid'] == '') {
                html += folder[i]['unid'];
                html += '" class="list-group-item active">';
            } else {
                html += folder[i]['unid'];
                html += '" class="list-group-item">';
            }
            html += folder[i]['filename'];
            var number = folder[i]['sum']==null?0:folder[i]['sum'];
            html += '<span class="badge">' + number;
            html += '</span></a>';
        }
        ;
        $("#Folders-content").html(html);
        click_search();
    });
    /*获取文件夹列*/
}
